import sys

from PySide6.QtCore import Signal
from PySide6.QtWidgets import QFrame, QApplication, QMessageBox, QDialog

from backend.db.database import SessionLocal
from backend.schemas.member_pydantic import MemberCreate
from backend.services.members_service import MemberService
from front.ui.ui_register import Ui_Frame


class Register(QDialog, Ui_Frame):

    refresh = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.initialization()
        self.doubleSpinBox.setRange(0, 10000)

    def initialization(self):
        self.pushButton.clicked.connect(self.click_save_button)

    def get_value(self) -> dict:
        """取值"""
        name = self.lineEdit.text().strip()
        phone_num = self.lineEdit_2.text().strip()
        initial_balance = self.doubleSpinBox.value()
        if not name or not phone_num:
            QMessageBox.warning(self, "警告", "缺少姓名或电话")
            return
        a = {"name": name,
             "phone_num": phone_num,
             "initial_balance": initial_balance,
             "note": self.lineEdit_3.text()}
        return a

    def click_save_button(self):
        try:
            value = self.get_value()
            if not value:
                return
            add_member=MemberCreate(**value)
            with SessionLocal() as session:
                member_service = MemberService(session)
                creatMember = member_service.create_member(add_member)
            QMessageBox.information(self, "提示", f'保存成功', )
            self.refresh.emit()
            self.deleteLater()
        except ValueError as e:
            QMessageBox.warning(self, "警告", f'手机号已存在', )


if __name__ == '__main__':
    app = QApplication([])
    win = Register()
    win.show()
    sys.exit(app.exec())
